package com.waimai.controller;

import com.waimai.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {


   String path ="E:\\javawab\\img";

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        log.info(file.toString());
        //创建UUID保证同一图片不被覆盖
        String s = UUID.randomUUID().toString();
        //原文件名
        String originalFilename = file.getOriginalFilename();
        //截取文件格式
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //看看原路径是否存在
        File file1 = new File(path);
        if (!file1.exists()){
            //不存在的情况下创建新的文件
            file1.mkdir();
        }
        String fileName = s+substring;
        try {
            file.transferTo(new File(path+fileName));
        } catch (Exception e) {
            e.printStackTrace();
        }


        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse httpServletResponse){
        try {
            //输入流 读取图片资源
            FileInputStream inputStream = new FileInputStream(new File(path+name));
            //输出流 通过输出流在浏览器里展示图片
            ServletOutputStream outputStream =httpServletResponse.getOutputStream();
            //设置写回浏览器格式
            httpServletResponse.setContentType("image/jpeg");
            int len =0;
            byte[] bytes = new byte[1024];
            while ((len=inputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
